package com.parseword1;

import java.util.HashMap;
import java.util.Map;

public class WordNodes {
	
	Map<Character,WordNode> nodes = new HashMap<Character,WordNode>(60);
	
	public void add(String text,WordHandler handler){
		char[] cs = text.toCharArray();
		Map<Character,WordNode> nodes = this.nodes;
		for (int i = 0; i < cs.length; i++) {
			char c = cs[i];
			WordNode node = null;
			if(!nodes.containsKey(c)){
				if(i == cs.length-1){
					nodes.put(c,node = new WordNode(c,handler));
				}else{
					nodes.put(c, node = new WordNode(c));
				}
			}else{
				node = nodes.get(c);
				if(i == cs.length-1){
					node.wordHandler = handler;
				}
			}
			nodes = node;
		}
	}
	
	public Object exec(String text,Object def){
		Object val = exec(text);
		if(val == null){
			return def;
		}
		return val;
	}
	public Object exec(String text){
		char[] cs = text.toCharArray();
		Map<Character,WordNode> nodes = this.nodes;
		int j = 0;
		WordHandler wordHandler = null;
		WordConfig word = null;
		for (int i = 0; i < cs.length; i++) {
			char c = cs[i];
			WordNode node = nodes.get(c);
			if(node == null){
				if(wordHandler!=null){
					return wordHandler.execute(word);
				}
				i = j;
				j++;
				nodes = this.nodes;
			}else if(node.wordHandler != null){
				word = new WordConfig();
				word.jumpText = String.valueOf(cs, 0, j);
				word.wordText = String.valueOf(cs, j, i-j+1);
				word.endText = String.valueOf(cs, i+1, cs.length-i-1);
				word.wordNodes = this;
				wordHandler = node.wordHandler;
			}else{
				nodes = node;
			}
		}
		if(wordHandler!=null){
			return wordHandler.execute(word);
		}
		return null;
	}
}
